<template>
    <div class="chat-container">
        <h2>聊天界面</h2>
        <div class="main-content">
            <div class="messages-area">
                <div class="chat-header">
                    <h3>当前用户：{{ username }}</h3>
                    <h3>{{ currentChatUser === 'all' ? '群聊' : `与 ${currentChatUser} 聊天` }}</h3>
                </div>
                <div class="messages-container">
                    <!-- 三元表达式 -->
                    <!-- <div v-if="roupedMessages.length === 0" class="empty-tip">暂无消息</div> -->
                    <!-- {{ groupedMessages[currentChatUser] }}
                    {{ groupedMessages[username] }} -->
                    <div v-for="msg in groupedMessages[currentChatUser] || []" :key="msg.id" class="message" :class="{
                        'own-message': msg.fromName === username,
                        'other-message': msg.fromName !== username
                    }">
                        <!-- {{ msg }} -->
                        <div class="sender">{{ msg.fromName }}:</div>
                        <div class="content">{{ msg.message }}</div>
                    </div>
                </div>

                <div class="input-area">
                    <input type="text" v-model="messageContent"
                        :placeholder="currentChatUser === 'all' ? '输入群聊消息...' : `输入给 ${currentChatUser} 的消息...`" />
                    <button @click="sendMessage">发送</button>
                </div>
            </div>

            <div class="users-area">
                <h2>用户列表</h2>
                <ul>
                    <li @click="selectUser('all')" :class="{ 'selected': currentChatUser === 'all' }">{{ '群聊' }}</li>
                    <li v-for="user in onlineUsers" :key="user" @click="selectUser(user)"
                        :class="{ 'selected': user === currentChatUser }">{{ user }}</li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, onUnmounted } from 'vue';

export default {
    name: 'ChatComponent',
    props: {
        username: {
            type: String,
            required: true
        }
    },
    setup(props) {
        const messageContent = ref('');
        const onlineUsers = ref([]);
        const currentChatUser = ref('all');
        let webSocket = null;

        const groupedMessages = ref({
            all: []
        });

        // 选择聊天用户
        const selectUser = (user) => {
            currentChatUser.value = user;
            console.log(`开始与 ${user} 聊天`);
        };

        // 连接WebSocket
        const connectWebSocket = () => {
            const wsUrl = `ws://localhost:8081/chat`;
            console.log('尝试连接WebSocket:', wsUrl);
            webSocket = new WebSocket(wsUrl);

            webSocket.onopen = () => {
                console.log('WebSocket连接成功');
                const heartbeatInterval = setInterval(() => {
                    if (webSocket && webSocket.readyState === WebSocket.OPEN) {
                        const pingMsg = JSON.stringify({ type: 'ping', timestamp: Date.now() });
                        console.log('发送心跳:', pingMsg);
                        webSocket.send(pingMsg);
                    } else {
                        clearInterval(heartbeatInterval);
                    }
                }, 10000);
            };

            webSocket.onmessage = (event) => {
                console.log('收到消息:', event.data);
                try {
                    const message = JSON.parse(event.data);
                    console.log('解析后的消息:', message);
                    if (message.type === 'pong') {
                        console.log('收到心跳响应');
                        return;
                    }
                    if (message.is_system) {
                        if (typeof message.message === 'string') {
                            let userStr = message.message.replace(/\[/g, '').replace(/\]/g, '');
                            try {
                                onlineUsers.value = JSON.parse(userStr);
                            } catch (e) {
                                onlineUsers.value = userStr.split(',').map(item => item.trim());
                            }
                        } else if (Array.isArray(message.message)) {
                            onlineUsers.value = message.message;
                        } else {
                            onlineUsers.value = [message.message];
                        }
                        onlineUsers.value = onlineUsers.value.filter(user => user !== props.username);
                        console.log('用户列表:', onlineUsers.value);
                    } else {

                        const msgObj = {
                            id: Date.now(),
                            fromName: message.fromName,
                            toName: message.toName,
                            message: message.message
                        };
                        console.log('收到非官方消息:', msgObj);
                        // console.log('message.to的类型：', typeof message.to, '值：', message.to); // 新增日志
                        if (message.toName === 'all') {
                            groupedMessages.value.all.push(msgObj);
                            console.log('群聊消息:', msgObj);
                        } else if (message.toName === props.username) {
                            console.log('收到来自', message.fromName, '的私聊消息:', msgObj);
                            if (!groupedMessages.value[message.toName]) {
                                groupedMessages.value[message.toName] = [];
                            }
                            groupedMessages.value[message.toName].push(msgObj);
                            if (!groupedMessages.value[message.fromName]) {
                                groupedMessages.value[message.fromName] = [];
                            }
                            groupedMessages.value[message.fromName].push(msgObj);
                        }
                    }
                } catch (error) {
                    console.error('解析消息失败:', error, '原始消息:', event.data);
                }
            };

            webSocket.onclose = (event) => {
                console.log('WebSocket连接关闭，代码:', event.code, '原因:', event.reason);
                if ([1000, 1001, 1005].includes(event.code)) {
                    console.log('正常关闭，不进行重连');
                } else {
                    setTimeout(() => {
                        console.log('尝试重新连接WebSocket...');
                        connectWebSocket();
                    }, 3000);
                }
            };

            webSocket.onerror = (error) => {
                console.error('WebSocket错误:', error);
            };
        };

        // 发送消息
        const sendMessage = () => {
            if (!messageContent.value.trim()) return;

            const message = {
                fromName: props.username,
                toName: currentChatUser.value,
                message: messageContent.value,
                timestamp: new Date().getTime()
            };

            if (webSocket && webSocket.readyState === WebSocket.OPEN) {
                webSocket.send(JSON.stringify(message));
                const msgObj = {
                    id: Date.now(),
                    fromName: props.username,
                    toName: currentChatUser.value,
                    message: messageContent.value
                };

                if (currentChatUser.value === 'all') {
                    groupedMessages.value.all.push(msgObj);
                } else {
                    if (!groupedMessages.value[currentChatUser.value]) {
                        groupedMessages.value[currentChatUser.value] = [];
                    }
                    groupedMessages.value[currentChatUser.value].push(msgObj);
                    if (!groupedMessages.value[props.username]) {
                        groupedMessages.value[props.username] = [];
                    }
                    groupedMessages.value[props.username].push(msgObj);
                }
                messageContent.value = '';
            } else {
                console.error('WebSocket未连接');
            }
        };

        // 组件卸载时关闭WebSocket连接
        onUnmounted(() => {
            if (webSocket) {
                webSocket.close();
            }
        });

        connectWebSocket();

        return {
            messageContent,
            onlineUsers,
            currentChatUser,
            groupedMessages,
            selectUser,
            sendMessage

        };
    }
};
</script>

<style scoped>
.chat-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
}

.main-content {
    display: flex;
    gap: 20px;
}

.messages-area {
    flex: 3;
    border: 1px solid #ccc;
    border-radius: 5px;
    overflow: hidden;
}

.users-area {
    flex: 1;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
}

.messages-container {
    height: 400px;
    overflow-y: auto;
    padding: 10px;
    background-color: #f9f9f9;
}

.input-area {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ccc;
}

.input-area input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px 0 0 4px;
}

.input-area button {
    padding: 8px 16px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
}

.users-area ul li {
    cursor: pointer;
    padding: 5px;
    border-radius: 3px;
}

.users-area ul li.selected {
    background-color: #42b983;
    color: white;
}

.message {
    min-height: 40px;
    min-width: 40px;
    height: auto;
    margin-bottom: 10px;
    padding: 8px;
    word-wrap: break-word;
    white-space: normal;
}

.own-message {
    background-color: #dff0d8;
    text-align: right;
    /* font-weight: 50px; */
}

.other-message {
    background-color: #f2dede;
    text-align: left;
    /* font-weight: 50px; */
}
</style>